﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

namespace blackhouse.WebNemo.Web {
    public class NemoPreviewFileModule : IHttpModule {

        public void Dispose() { }

        public void Init(HttpApplication context) {
            context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
        }

        void context_AuthorizeRequest(object sender, EventArgs e) {
            string url = HttpContext.Current.Request.RawUrl;
            if (url.Contains("getnemofile/"))
                this.RewriteDownload(url);
            if (url.Contains("prevnemofile/"))
                this.RewritePreview(url);

        }

        private void RewriteDownload(string url) {
            Regex r = new Regex(@"(getnemofile)/(.[^/]*)/(.[^/]*)/(\d*)/(.*)");
            Match m = r.Match(url);
            if (m.Success) {
                string newUrl = string.Format("/NemoDownloadFile.ashx?table={0}&column={1}&recordId={2}", m.Groups[2].Value, m.Groups[3].Value, m.Groups[4].Value);
                HttpContext.Current.RewritePath(newUrl);
            }
        }

        private void RewritePreview(string url) {
            Regex r = new Regex(@"(prevnemofile)/(.[^/]*)/(.[^/]*)/(\d*)/(.*)");
            Match m = r.Match(url);
            if (m.Success) {
                string newUrl = string.Format("/NemoPreviewFile.ashx?table={0}&column={1}&recordId={2}", m.Groups[2].Value, m.Groups[3].Value, m.Groups[4].Value);
                HttpContext.Current.RewritePath(newUrl);
            }
        }

    }
}